<template>
  <div id="labmaininfobac" style="height: 100%">
    <div class="bodyContent">
      <div class="area margin-top-xs">
        <Splitpanes class="Splitpanes-Panel" :dbl-click-splitter="false">
          <Pane :size="patInfoPanelSize">
            <Splitpanes horizontal :dbl-click-splitter="false" style="height: calc(100%)">
              <Pane size="92">
                <vxe-toolbar class-name="bg-grey light" :className="notCurDay ? 'bg-yellow light' : 'bg-grey light'">
                  <template #buttons>
                    <div class="padding-lr-xs">
                      <vxe-form ref="xBacFormBase" class-name="bg-grey light"
                        :className="notCurDay ? 'bg-yellow light' : 'bg-grey light'" title-align="left" title-width="60"
                        :data="form">
                        <vxe-form-item title="报告单元" span="24" field="rptGroup">
                          <template #title>
                            <span class="text-bold rpt-group-setting cursor" @dblclick="rptDbClick">报告单元</span>
                          </template>
                          <template #default>
                            <SelectWorkGroupBac :url="'/api/rptGroup/findRptGroupList'" style="width: 100%"
                              :inputWidth="'100%'" :businessType="'20'" @getSelectedId="getSelectedId">
                            </SelectWorkGroupBac>
                          </template>
                        </vxe-form-item>
                        <vxe-form-item title="检测时间" span="24" field="sampleda">
                          <template #default="{ data }">
                            <vxe-input v-model="data.sampleda" type="date" :value-format="'yyyy-MM-dd'"
                              :label-format="'yyyy-MM-dd'" clearable transfer @change="timeChange"></vxe-input>
                          </template>
                        </vxe-form-item>
                        <vxe-form-item title="标本号" span="24" field="sampleNo">
                          <template #default="{ data }">
                            <vxe-input ref="codeInput" :class="() => { }" v-model="data.sampleNo" clearable
                              @keydown="handleSearchByCode" @blur="handleSearchByCode" @focus="() => { }"></vxe-input>
                          </template>
                        </vxe-form-item>
                        <vxe-form-item title="条码号" span="24" field="reqNo">
                          <template #default="{ data }">
                            <vxe-input ref="reqNoInput" :class="() => { }" lang="en-US" v-model="data.reqNo"
                              :disabled="form.isChk === 1 || form.isChk === 2" clearable @input="(params) => { }"
                              @keydown="handleSearchByReqno"></vxe-input>
                          </template>
                        </vxe-form-item>
                      </vxe-form>
                    </div>
                  </template>
                </vxe-toolbar>
                <MainInfoEditPanelBac ref="bacMainInfoEditPanelRef" :currentMainInfoObj="currentMainInfo"
                  @UpdateSuccessCallback="mainInfoUpdateSuccessCallback"
                  @validateTestChkDoctorSuccess="validateTestChkDoctorSuccess" />
              </Pane>
              <Pane size="12">
                <div class="padding-lr-xs">
                  <vxe-toolbar>
                    <template #buttons>
                      <span class="text-bold">状态:</span>
                      <span class="padding-lr-xs">{{ chkStatus }}</span>
                      <span class="padding-lr-xs">{{ isPrinted }}</span>
                    </template>
                    <template #tools v-if="false">
                      <span class="text-bold text-red margin-right-xs">有未处理危急值</span>
                    </template>
                  </vxe-toolbar>
                  <vxe-toolbar>
                    <template #buttons>
                      <span class="text-bold">收费:</span>
                      <span class="padding-lr-xs">已收费</span>
                    </template>
                    <template #tools>
                      <span class="text-bold">总金额:</span>
                      <span class="padding-lr-xs text-price">{{ costTotal }}</span>
                    </template>
                  </vxe-toolbar>
                  <vxe-toolbar>
                    <template #buttons>
                      <div class="flex justify-start text">
                        <span class="text-bold">检验医师:</span>
                        <span class="padding-lr-xs text-shadow text-bold text-orange">{{ testChkDoctorObj.testDoctorNa
                        }}</span>
                      </div>
                    </template>
                    <template #tools>
                      <div class="flex justify-start text">
                        <span class="text-bold">审核医师:</span>
                        <span class="padding-lr-xs text-shadow text-bold text-orange">{{ testChkDoctorObj.chkDoctorNa
                        }}</span>
                      </div>
                    </template>
                  </vxe-toolbar>
                </div>
              </Pane>
            </Splitpanes>
          </Pane>
          <Pane :size="resultSize">
            <!-- <el-tabs v-if="!IsEmpty(curreFlowNode)" v-model="editableTabsValue" @tab-click="tabHandleClick" type="card" editable class="lab-bac-test-result-tab el-tab-sm">
              <template #add-icon>
                <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="新增方案" @click="insertWkflw"></vxe-button>
              </template>
              <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name"></el-tab-pane>
            </el-tabs> -->
            <vxe-toolbar class-name="lines-orange dashed line-orange">
              <template #buttons>
                <vxe-button type="text" class="button-blue margin-lr-xs" :content="'刷新'"
                  @click="actionBtnsClickGlobal('refreshCurrentRow')"></vxe-button>
                <vxe-button type="text" class="button-blue margin-lr-xs" :content="'上一个'"
                  @click="actionBtnsClickGlobal('prevCode')"></vxe-button>
                <vxe-button type="text" class="button-blue margin-lr-xs" :content="'下一个'"
                  @click="actionBtnsClickGlobal('nextCode')"></vxe-button>
                <!-- <vxe-button type="text" class="button-blue margin-lr-xs" :content="'初审'" @click="actionBtnsClickGlobal('nextCode')"></vxe-button> -->
                <vxe-button type="text" v-if="currentMainInfo.isChk < 2 || !currentMainInfo || !currentMainInfo.isChk"
                  class="button-blue margin-lr-xs" :content="'审核'" @click="actionBtnsClickGlobal('chkMainInfo')"
                  :loading="chkLoading"></vxe-button>
                <vxe-button type="text" v-if="currentMainInfo.isChk === 2" class="button-red margin-lr-xs"
                  :content="'取消审核'" @click="actionBtnsClickGlobal('unChkMainInfo')"></vxe-button>
                <vxe-button type="text" class="button-blue margin-lr-xs" :content="'批量扫码'"
                  @click="actionBtnsClickGlobal('scanCodeBulk')"></vxe-button>
                <vxe-button type="text" class="button-blue margin-lr-xs" :content="'患者360视图'"
                  @click="actionBtnsClickGlobal('getWlEhrName')"></vxe-button>
              </template>
            </vxe-toolbar>
            <div class="flex justify-start cursor" v-if="!IsEmpty(curreFlowNode)">
              <div class="padding-sm same-skin-box border-radius margin-right-xs" style="width: 30%; position: relative"
                :class="layoutSkin">
                <div class="text-bold text-df text-shadow text-cut text-white">{{ `${editableTabs && editableTabs.length >
                  0 ? editableTabs[0].title : '暂无方案'}` }}</div>
                <div class="flex justify-end" style="position: absolute; bottom: 2px; left: 5px">
                  <vxe-button type="text" icon="vxe-icon-sort" class="button-blue margin-lr-xs text-xs"
                    class-name="margin-lr-xs" content="切换方案" @click="insertWkflw"
                    :disabled="resultIsDisabled()"></vxe-button>
                </div>
              </div>
              <FlowStepComp v-if="!IsEmpty(curreFlowNode)" :tabs="processTabs" style="width: 100%" @itemClick="itemClick"
                @addItemClick="addItemClick" ref="flowStepCompRef" />
            </div>

            <RptResultBac ref="RptResultBacRef" style="height: calc(100% - 30px)"
              v-if="!IsEmpty(curreFlowNode) && curreFlowNode.pageCode == 'RptResultBac'"
              :pageCode="curreFlowNode.pageCode" @actionBtnsClick="actionBtnsClick"
              @selectBacDrugResultTemplate="selectBacDrugResultTemplate" @getAddFeeCnt="getAddFeeCnt"
              @currentRow="currentRow" />
            <RptCultiObserResult ref="RptCultiObserResultRef"
              v-if="!IsEmpty(curreFlowNode) && curreFlowNode.pageCode == 'RptCultiObserResult'"
              :pageCode="curreFlowNode.pageCode" @actionBtnsClick="actionBtnsClick"
              @selectBacDrugResultTemplate="selectBacDrugResultTemplate" @imageUploadSuccess="imageUploadSuccess"
              @currentRow="currentRow" style="height: calc(100% - 29px - 60px)" />
            <RptStainingResult ref="RptStainingResultRef"
              v-if="!IsEmpty(curreFlowNode) && curreFlowNode.pageCode == 'RptStainingResult'"
              :pageCode="curreFlowNode.pageCode" @actionBtnsClick="actionBtnsClick"
              @selectBacDrugResultTemplate="selectBacDrugResultTemplate" @imageUploadSuccess="imageUploadSuccess"
              style="height: calc(100% - 29px - 60px)" />
            <!-- <RptInstrCultiResult ref="RptInstrCultiResultRef" v-if="!IsEmpty(curreFlowNode)&&curreFlowNode.pageCode == 'RptInstrCultiResult'" :pageCode="curreFlowNode.pageCode" @actionBtnsClick="actionBtnsClick" @selectBacDrugResultTemplate="selectBacDrugResultTemplate" /> -->
            <RptBloodCulResult ref="RptInstrCultiResultRef"
              v-if="!IsEmpty(curreFlowNode) && curreFlowNode.pageCode == 'RptInstrCultiResult'"
              :pageCode="curreFlowNode.pageCode" @actionBtnsClick="actionBtnsClick"
              @selectBacDrugResultTemplate="selectBacDrugResultTemplate" @subcultivation="subcultivation"
              @currentRow="currentRow" />
            <BacRptOverview ref="rptOverviewRef" v-if="!IsEmpty(curreFlowNode) && curreFlowNode.pageCode == 'rptOverview'"
              :pageCode="curreFlowNode.pageCode" @actionBtnsClick="actionBtnsClick"
              @confirmRptPrint="rptOverviewPrintReport" />
          </Pane>
          <Pane :size="patInfoFieldSize">
            <el-tabs class="lab-maininfo-right-tab el-tab-sm" type="border-card" @tab-click="templateClick">
              <el-tab-pane label="列表">
                <TestListBac ref="testListRef" @mainInfoRowChange="mainInfoRowChange" @getReqRptResult="reqRptResult"
                  @getLabMainInfoList="labMainInfoList" @IschkLoading="IschkLoading" @autoPrint="autoPrint" />
              </el-tab-pane>
              <el-tab-pane label="图片">
                <ImageResult ref="imageRef" @SelectedCallback="imgSelectedCallback" />
              </el-tab-pane>
              <el-tab-pane label="费用">
                <Cost ref="costRef" />
              </el-tab-pane>
              <!-- <el-tab-pane label="模板"> 费用 </el-tab-pane> -->
              <el-tab-pane label="流程记录"> 流程记录 </el-tab-pane>
              <el-tab-pane label="操作日志">
                <BacLabMainInfoLog ref="LabMainInfoLogRef" />
              </el-tab-pane>
            </el-tabs>
          </Pane>
        </Splitpanes>
      </div>
    </div>
    <!-- 批量扫码 -->
    <WkltInsertByScanCodeRef ref="bacScanCodeDlgRef" @refreshLabMinInfo="refreshLabMinInfo" />
    <!-- 列表字段顺序控制 -->
    <WkltConfig ref="bacTestListConfigRef" :suitModule="'2'" @refreshFields="refreshFields" />
    <!-- 流程方案切换 -->
    <WkflwSelection ref="WkflwSelectionRef" @change="changeSuccess" />
    <!-- 转种流程方案节点选择 -->
    <WkflwNodeSelection ref="WkflwNodeSelectionRef" />
    <!-- 静默打印 -->
    <QuietPrint ref="quietPrintRef" :printParams="printParamsObj" />
    <!-- 报告预览组件 -->
    <MultiRptPreview :reportList="reportList" :toggle="isPreviewRpt" :modalTitle="'报告预览'" />
    <!-- 危机值上报 -->
    <BacAlarmReport ref="criticalReportRef" @treatFinish="alarmTreatFinish" />
    <!-- 药敏模板组合 -->
    <BacDrugResultTempModal ref="BacDrugResultTempModalRef" @confirm="drugTemplateConfirm" />
    <!-- 审核密码授权 -->
    <ChkAuthComp ref="ChkAuthCompRef" @AuthSuccess="chkConfirm" />
    <!-- 授权验证组件 -->
    <AuthValidateComp ref="AuthValidateCompRef" @unChkConfirm="unChkConfirm" />
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, getCurrentInstance, onMounted, computed, watch } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VXETable } from 'vxe-table';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import XEClipboard from 'xe-clipboard';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { IsEmpty, formatDateTime, autoIncrementNumber } from '@/utils/common';
import { ProcessRightMenu } from './LabMainInfoBacUtils';
import WkltConfig from '@/views/lab_sys/lab_bus/components/WkltConfig.vue'; //检验记录界面配置
import WkltInsertByScanCodeRef from '@/views/lab_sys/lab_bus/components/WkltInsertByScanCodeRef.vue'; //批量扫码
import BacAlarmReport from '@/views/lab_sys/bac_bus/components/BacAlarmReport.vue'; //微生物危急值报告
import SelectWorkGroupBac from '@/views/lab_sys/lab_bus/components/SelectWorkGroupBac.vue'; //报告单元引入下拉组件
import MainInfoEditPanelBac from '@/components/MainInfoEditPanelBac.vue';
import { GetGolbalOptions, GetRptGroupOptions, GetRptGroupOptionsAsync } from '@/utils/SysOptionsHelper';
import { getOptionValueByCodeGlobalOption, getOptionValueByCodeRptGroupOption } from '@/utils/SysOptionsHelper';
import NodeComp from './components/NodeComp.vue';
import ColoMphy from './components/ColoMphy.vue';
import RptResultBac from './components/RptResultBac.vue'; /**鉴定结果 */
import RptCultiObserResult from './components/RptCultiObserResult.vue'; /**培养观察结果(按菌落形态) */
import RptInstrCultiResult from './components/RptInstrCultiResult.vue'; /**仪器培养(血培养) */
import RptBloodCulResult from './components/RptBloodCulResult.vue'; /**仪器培养(血培养) */
import RptStainingResult from './components/RptStainingResult.vue'; /**染色 */
import BacLabMainInfoLog from '../lab_bus/components/BacLabMainInfoLog.vue';
import TestListBac from './components/TestListBac.vue';
import { AppStore } from '@/stores/store';
import { SysOptions } from '@/stores/sysoptions';
import FlowStepComp from '@/components/FlowStepComp.vue';
import WkflwSelection from './components/WkflwSelection.vue';
import QuietPrint from '@/components/QuietPrint.vue'; /**静默打印组件 */
import MultiRptPreview from '@/components/MultiRptPreview.vue'; /**报告预览组件 */
import WkflwNodeSelection from './components/WkflwNodeSelection.vue';
import BacDrugResultTempModal from './components/BacDrugResultTempModal.vue'; /**药敏结果模板 */
import BacRptOverview from './components/BacRptOverview.vue'; /* 报告查询 */
import { tabBarProps } from 'element-plus';
import ImageResult from '@/views/lab_sys/bac_bus/components/ImageResult.vue';
import Cost from './components/Cost.vue';
import ChkAuthComp from '@/components/ChkAuthComp.vue';
import AuthValidateComp from '@/components/AuthValidateComp.vue'; //AuthValidateComp
import { toJSONString } from 'xe-utils';
import { saveProcessLogs } from '@/utils/BacProcessLogHelper';
import { initWebSocket } from '@/utils/websocket';

let { proxy }: any = getCurrentInstance();
let $this = {} as any;
const storeObj = AppStore();
const sysoptionObj = SysOptions(); //系统参数状态管理对象
const bacTestListConfigRef = ref(null); //列顺序配置字段
const testListRef = ref(null); /**检验列表ref对象 */
const flowStepCompRef = ref(null);
const proRightMenu = reactive(ProcessRightMenu());
const RptResultBacRef = ref(null); /**细菌-抗生素检验结果组件对象 */
const WkflwSelectionRef = ref(null); /**选择流程方案弹窗组件对象 */
const WkflwNodeSelectionRef = ref(null); /**转种选择流程方案节点 */
const bacScanCodeDlgRef = ref(null); /**批量扫码弹窗对象 */
const quietPrintRef = ref(null); /**静默打印组件对象 */
const criticalReportRef = ref(null); /**危急值上报组件对象 */
const BacDrugResultTempModalRef = ref(''); /**药敏结果模板对象 */
const RptCultiObserResultRef = ref(null); /**培养观察(按菌落形态) */
const RptInstrCultiResultRef = ref(null); /**仪器培养(血培养) */
let LabMainInfoLogRef: any = ref(null); //操作日志
const RptStainingResultRef = ref(null);
const rptOverviewRef = ref(null); /* 报告查询节点页面 */
//const RptBloodCulResultRef = ref(null);/**血培养节点 */
const ChkAuthCompRef = ref(null); /**审核确认弹窗 */
let editableTabsValue = ref(null);
let sltWorkFlow = ref(null);
let editableTabs = reactive([]);
let processTabs = reactive([]);
let setploading = ref(false);
let imageRef: any = ref(null); //图片ref
let costRef: any = ref(null); //费用传值
let AuthValidateCompRef = ref(null); //授权验证弹窗对象
let layoutSkin = ref(storeObj.layoutSkin);
let wkltConfigForm = reactive({
  visible: false,
  rptGroup: '',
  rptGroupName: ''
});
let chkLoading = ref(false);
let patInfoPanelSize: any = ref(20); //病人信息列宽度
let resultSize: any = ref(60); //结果信息列宽度
let patInfoFieldSize: any = ref(20); //字段列表信息列宽度
let xBacFormBase = ref(null);
let isShowSettingBtn = ref(false); //是否显示设置按钮
let testChkDoctorObj = reactive({ testDoctor: '', testDoctorNa: '', chkDoctor: '', chkDoctorNa: '' });
let notCurDay = ref(false); //是否当天
let reqNoInput = ref(null); //条码号输入框对象
let curreFlowNode = ref(null);
let form: any = reactive({
  id: '',
  sampleda: formatDateTime(new Date(), 'yyyy-MM-dd'),
  sampleNo: formatDateTime(new Date(), 'yyMMdd') + '0001', //'1',
  reqNo: '',
  rptGroup: '1734518183946776577'
});
let isPreviewRpt = ref(false); /**是否预览报告 */
let reportList = reactive([]); /**生成报告集合，预览报告时使用 */
let bacMainInfoEditPanelRef = ref(null);
let currentMainInfo: any = reactive({});
let printParamsObj = ref(null); /**静默打印参数 */
let chkBeforePrint = ref(false); /**是否打印前的自动审核 */
let alarmReportBeforeChk = ref(false); /**是否审核审核前上报危急值 */
let mainInfoTopPanel = ref(100); /**检验主记录列表面板 */
let isShowItemTemplatePanel = ref(false); /**是否显示项目模板面板 */
let isTipsExistAlarm = ref(false);

watch(
  () => storeObj.chkDoctorObj,
  (n, o) => {
    if (!IsEmpty(n.code)) {
      testChkDoctorObj.chkDoctor = n.code;
    }
    if (!IsEmpty(n.name)) {
      testChkDoctorObj.chkDoctorNa = n.name;
    }
  },
  { deep: true, immediate: true }
);
watch(
  () => storeObj.testDoctorObj,
  (n, o) => {
    if (!IsEmpty(n.code)) {
      testChkDoctorObj.testDoctor = n.code;
    }
    if (!IsEmpty(n.name)) {
      testChkDoctorObj.testDoctorNa = n.name;
    }

    /**如果会话存储中没有记忆值，取当前登陆人 */
    if (IsEmpty(testChkDoctorObj.testDoctor)) {
      const locRemObj = localStorage.getItem('userInfo');
      if (!IsEmpty(locRemObj)) {
        const locRemObjEntry = JSON.parse(locRemObj);
        if (!IsEmpty(locRemObjEntry.username)) {
          testChkDoctorObj.testDoctor = locRemObjEntry.username;
        }
        if (!IsEmpty(locRemObjEntry.realname)) {
          testChkDoctorObj.testDoctorNa = locRemObjEntry.realname;
        }
      }
    }
  },
  { deep: true, immediate: true }
);

watch(
  () => storeObj.layoutSkin,
  (n, o) => {
    // 将获取的新值动态赋给layoutcolor
    layoutSkin.value = n;
  },
  { deep: true, immediate: true }
);

/**左下角审核状态 */
let chkStatus = computed(() => {
  if (!currentMainInfo || IsEmpty(currentMainInfo.isChk)) {
    return '未审核';
  } else if (!IsEmpty(currentMainInfo.isChk) && currentMainInfo.isChk === 1) {
    return '已初审';
  } else if (!IsEmpty(currentMainInfo.isChk) && currentMainInfo.isChk === 2) {
    return '已审核';
  } else {
    return '未审核';
  }
});
/**计算属性是否打印 */
let isPrinted = computed(() => {
  if (!currentMainInfo || IsEmpty(currentMainInfo.isPrint)) {
    return '未打印';
  } else if (!IsEmpty(currentMainInfo.isPrint) && currentMainInfo.isPrint === 1) {
    return '已打印';
  } else {
    return '未打印';
  }
});
/**获取费用合计 */
let costTotal = computed(() => {
  if (!currentMainInfo || IsEmpty(currentMainInfo.isChk)) {
    return '0.00';
  }
  const a = costRef.value?.getCostTotal();
  return IsEmpty(a) ? '' : a.toFixed(2);
});

onMounted(() => {
  if (storeObj.userInfo && storeObj.userInfo.username && storeObj.userInfo.username.includes('admin')) {
    isShowSettingBtn.value = true;
  }
  getmoduleWidth();
  // getBacSampleNo();
  initWebSocket(null);
});

async function getBacSampleNo() {
  const url = '/lab/wlConfig/getBacSampleNoByRule';
  const res: any = await proxy.$http.get(url, { params: { sampleDa: form.sampleda + ' 00:00:00', rptGroup: form.rptGroup } });
  form.sampleNo = res.data;
}

/**列顺序修改完成回调 */
function refreshFields(refreshFields: any) {
  if (refreshFields) {
    getmoduleWidth();
  }
}

/**修改报告单元列顺序触发 */
function rptDbClick() {
  wkltConfigForm.visible = true;
  bacTestListConfigRef.value?.wkltConfigData(wkltConfigForm);
}

function IschkLoading(flag) {
  if (flag == 1) {
    chkLoading.value = true;
  } else {
    chkLoading.value = false;
  }
}

/**获取模块面板宽度 */
function getmoduleWidth() {
  const url = '/lab/wlConfig/findWlConfigSizeAndHeight';
  const data = {
    suitModule: '2',
    rptGroup: form.rptGroup
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      if (res.data !== null) {
        patInfoPanelSize.value = res.data.patsPanelSize * 100;
        resultSize.value = res.data.resultsPanelSize * 100;
        patInfoFieldSize.value = 100 - patInfoPanelSize.value - resultSize.value;
        patInfoFieldDecimalSize = res.data.workbenchPanelSize;
      } else {
        patInfoPanelSize.value = 15;
        resultSize.value = 65;
        patInfoFieldSize.value = 20;
      }
      // patInfoPanelSize.value = 15;
      // resultSize.value = 65;
      // patInfoFieldSize.value = 20;
    })
    .catch((err: any) => { });
}
/**右键菜单单击事件 */
function contextMenuClickEvent() {
  //todo
}
/**报告单元选中改变事件
 * @param selectedRadioId 报告单元Id
 * @param selectedName 报告单元名称
 */
async function getSelectedId(selectedRadioId: { value: string }, selectedName: { value: string }) {
  await GetRptGroupOptionsAsync(selectedRadioId.value);
  form.id = '';
  form.rptGroup = selectedRadioId.value;
  form.reqNo = '';
  wkltConfigForm.rptGroup = selectedRadioId.value;
  wkltConfigForm.rptGroupName = selectedName.value;
  bacMainInfoEditPanelRef.value.getWkltConfigList(form.rptGroup);

  testListRef.value?.initPage(form);
}
/**检验日期选择发生改变
 *
 */
function timeChange() {
  //getBacSampleNo();
  const a = formatDateTime(new Date(), 'yyyy-MM-dd');
  const sa = formatDateTime(form.sampleda, 'yyyy-MM-dd');
  if (a !== sa) {
    notCurDay.value = true;
  } else {
    notCurDay.value = false;
  }
  form.reqNo = '';
  /**重置全局选择日期时间 Pina  LocalhostSession */
  //testListRef.value.initPage(form);
  /**刷新检验记录 */
  /* 选中当天的第一条记录 */
  const result = testListRef.value?.timeChangeSetSelectItem(sa);
  if (result === false && result !== undefined) {
    form.sampleNo = `${formatDateTime(form.sampleda, 'yyMMdd')}0001`;
    form.reqNo = '';
    clearPatResultInfos();
    editableTabs.length = 0;
    editableTabsValue.value = null;
    processTabs.length = 0;
    curreFlowNode.value = {};
    sltWorkFlow.value = {};
  }
}

function handleSearchByReqno({ value, $event }: any) {
  if ($event.keyCode === 13) {
    if (!IsEmpty(value)) {
      form.reqNo = value;
    }
    //$this['nextCode']();
    testListRef.value?.baseInfoChange(4, value, form, (scanRes) => {
      if (scanRes !== undefined && scanRes === false && !IsEmpty(value)) {
        reqNoInput.value?.focus();
        return;
      }
      $this['nextCode']();
    });
    return;
  }
}
/**节点点击事件 */
function itemClick(m: { id: any; pageCode: any } | null) {
  curreFlowNode.value = m;
  processTabs.forEach((mm) => {
    if (mm.id === m.id) {
      mm.isActive = true;
    } else {
      mm.isActive = false;
    }
  });
  proxy.$nextTick(() => {
    const rObj: any = proxy.$refs[`${m.pageCode}Ref`];
    if (rObj) {
      let data = {} as any;
      Object.assign(data, currentMainInfo);
      data['nodeNo'] = curreFlowNode.value.nodeNo;
      data['testFlowNo'] = curreFlowNode.value.testFlowNo;
      rObj?.initPage(data, Object.assign({}, m), sltWorkFlow);
    }
  });
}
/**添加节点事件触发 */
function addItemClick(m: { id: any } | null) {
  curreFlowNode.value = m;
  processTabs.forEach((mm) => {
    if (mm.id === m.id) {
      mm.isActive = true;
    } else {
      mm.isActive = false;
    }
  });
  //VxeMessage('再次之后添加节点', VxeNotifyType.success);
  WkflwNodeSelectionRef.value?.showModal();
}
/**向TestList子组件传递表单值 */
function handleSearchByCode({ value, $event }: any) {
  if ($event.keyCode === 13) {
    form.reqNo = '';
    testListRef.value?.baseInfoChange(3, value, form, async () => {
      //#region  Name
      if (true) {
        /**没有选中，查询数据库，是否是否有该条记录 */
        const res = await testListRef.value?.findLabMainInfoByPrimaryData(form.rptGroup, form.sampleda, form.sampleNo);
        if (res && res.length > 0) {
          Object.assign(form, res[0]);
          Object.assign(currentMainInfo, res[0]);
          bacMainInfoEditPanelRef.value?.currentMainInfoChange(res[0]);
          // if (rptResultRef.value) {
          //   rptResultRef.value?.initTestList(form, false); //传递给右侧基本信息表单
          // }
        }
        if (!res) {
          /**如果下一个标本，则清空中间结果 */
          clearPatResultInfos();
        }
      }
      //#endregion
    });

    reqNoInput.value?.focus();
  }
}
/**病人信息修改保存成功回调
 * @row 已修改的检验记录信息
 */
function mainInfoUpdateSuccessCallback(row: any) {
  if (testListRef.value) {
    testListRef.value?.updateMainInfoRow(row);
  }
}
/**左侧修改病人信息 检测医生 审核医生验证成功后调用 */
function validateTestChkDoctorSuccess(e: any) {
  /**只修改当前标本 e.edtType===1*/
  /**修改所有未审核标本 e.edtType===2*/
  /**修改指定标本号范围 e.edtType===3*/
  testListRef.value?.refreshMainInfoListM3(e, false, false);
}
/**检验记录 */
function actionCLick(item: any) {
  // if ($this[item.event]) {
  //   $this[item.event]();
  // }
}
/**上传图片后重新加载 */
function imageUploadSuccess() {
  imageRef.value.getImageData(form);
}
/**组件之间调度 */
function mainInfoRowChange(row: any) {
  Object.assign(form, row);
  Object.assign(currentMainInfo, row);
  bacMainInfoEditPanelRef.value?.currentMainInfoChange(row);
  if (RptResultBacRef.value) {
    RptResultBacRef.value?.initPage(row);
  }
  imageRef.value.getImageData(form);
  costRef.value.getreqDetail(form);
  LabMainInfoLogRef.value.initForm(form);
  //查询流程方案
  if (!IsEmpty(row)) {
    findBacTestWorkFlowList();
  } else {
    editableTabs.length = 0;
    editableTabsValue.value = null;
    processTabs.length = 0;
    curreFlowNode.value = {};
    sltWorkFlow.value = {};
  }
}
function findBacTestWorkFlowList() {
  editableTabs.length = 0;
  editableTabsValue.value = null;
  processTabs.length = 0;
  curreFlowNode.value = {};
  sltWorkFlow.value = {};
  const url = '/api/bac/bac-test-work-flow/findBacTestWorkFlowList';
  proxy.$http
    .get(url, { params: { reqNo: currentMainInfo.reqNo, rptGroup: currentMainInfo.rptGroup, sampleNo: currentMainInfo.sampleNo, sampleda: formatDateTime(currentMainInfo.sampleda, 'yyyy-MM-dd hh:mm:ss') } })
    .then(async (res: any) => {
      processTabs.length = 0;
      const wfList = res.data;
      if (!IsEmpty(wfList) && wfList.length > 0) {
        for (const wf of wfList) {
          editableTabs.push({
            title: wf.workFlowNa,
            name: wf.id,
            workFlowNo: wf.workFlowNo,
            bacTestWorkFlowNodes: wf.bacTestWorkFlowNodes,
            cultureCombinationIds: IsEmpty(wf.culCombinaNos) ? [] : wf.culCombinaNos.split(',')
          });
        }
        editableTabsValue.value = editableTabs[0].name;
        if (!IsEmpty(editableTabs[0].bacTestWorkFlowNodes) && editableTabs[0].bacTestWorkFlowNodes.length > 0) {
          processTabs.push(...editableTabs[0].bacTestWorkFlowNodes);

          const specNodeObj = { id: '', sampleNo: null, rptGroup: '', sampleda: '', testFlowNo: '', reqNo: '', nodeNo: '', workFlowId: '', workFlowNodeDictNo: '', workFlowNodeDictNa: '', nodeUrl: null, seq: null, nodeDictId: '', nodeTypeNo: '', nodeTypeNa: '', nodeDictCode: '', nodeDictName: '', displayFlag: '', displayColor: '', codePrefix: null, codeRuleNo: null, isPrintLabel: 1, labelTemplateNo: null, explain: '', pageName: '', operation: '', isActive: false, pageCode: '', nodeDictSeq: '' };
          Object.assign(specNodeObj, processTabs[processTabs.length - 1]);
          specNodeObj.pageName = `报告汇总`;
          specNodeObj.nodeDictName = `报告汇总`;
          specNodeObj.pageCode = `rptOverview`;
          specNodeObj.isActive = false;
          specNodeObj.id = '';
          processTabs.push(specNodeObj);
          sltWorkFlow.value = editableTabs[0];
          console.log('sltWorkFlow', sltWorkFlow.value);
          console.log('processTabs', processTabs);

          //查找当前流程节点
          if (!IsEmpty(processTabs) && processTabs.length > 0) {
            curreFlowNode.value = processTabs.find((item) => item.isActive);
            console.log('curreFlowNode', curreFlowNode.value);

            proxy.$nextTick(() => {
              const rObj: any = proxy.$refs[`${curreFlowNode.value.pageCode}Ref`];
              if (rObj) {
                let data = {} as any;
                Object.assign(data, currentMainInfo);
                data['nodeNo'] = curreFlowNode.value.nodeNo;
                data['testFlowNo'] = curreFlowNode.value.testFlowNo;
                rObj?.initPage(data, curreFlowNode.value, sltWorkFlow);
              }
            });
          }
        }
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
function tabHandleClick(tab: { props: { name: any } }) {
  processTabs.length = 0;
  const obj = editableTabs.find((item) => item.name == tab.props.name);
  sltWorkFlow.value = obj;
  processTabs.push(...obj.bacTestWorkFlowNodes);
}
//传值到父
function labMainInfoList(val: any) {
  scanCodeForm.wl = val;
}
//传值到RptResult.vue界面
function reqRptResult(val: any) {
  if (val !== null) {
    Object.assign(form, val);
    imageRef.value.getImageData(form);
    costRef.value.getreqDetail(form);
    LabMainInfoLogRef.value.initForm(form);
    // rptResultRef.value.initTestList(form); //传递给右侧基本信息表单
  } else {
    /**下一个标本，需要清空中间的结果 */
    form.id = null;
    imageRef.value.getImageData(form);
    costRef.value.getreqDetail(form);
    LabMainInfoLogRef.value.initForm(form);
    // rptResultRef.value.initTestList(form); //传递给右侧基本信息表单
  }
}
/**功能按钮点击事件 */
function actionBtnsClick(e: { event: string | number; paramObj: any }) {
  if ($this[e.event]) {
    $this[e.event](e.paramObj);
  }
}
/**功能按钮点击事件 */
function actionBtnsClickGlobal(eventCode: string | number) {
  if ($this[eventCode]) {
    $this[eventCode]();
  }
}


let cultureTableList: any = reactive([]);
//自动打印标签
function autoPrint() {
  console.log('自动打印标签====>>>>>', form.reqNo);
  let reqInfo;

  if (!form.reqNo) {
    return;
  }
  reqInfo = form.reqNo;
  cultureTableList.length = 0;
  const url = '/api/bac/bac-test-culture-medium/findBacTestCultureMediumList';
  proxy.$http
    .get(url, { params: { reqNo: form.reqNo } })
    .then(async (res: any) => {
      Object.assign(cultureTableList, res.data);

      let reportId: any;
      if (cultureTableList.length > 0) {
        let url = `/api/pubReport/getReportByBusFormCode?code=006`;
        proxy.$http
          .get(url)
          .then((res: any) => {
            if (res && res.status && res.status.code === 1 && res.data && !IsEmpty(res.data.id)) {
              reportId = res.data.id;
              let i = 0;
              cultureTableList.forEach((sltRow: any) => {
                console.log('sltRow====>>>>>',reqInfo);
                
                if (!sltRow.isPrintLabels) {
                  let num = 1;
                  let report = reportId;
                  if (!IsEmpty(sltRow.tagsNum)) {
                    num = sltRow.tagsNum;
                  }
                  if (!IsEmpty(sltRow.mediumTag)) {
                    report = sltRow.mediumTag;
                  }
                  const param = [{ ReportName: report, ReportParameters: [{ Name: 'code', Value: reqInfo }], PdfPrinterSetting: { PdfPrinterCopies: num } }];
                  setTimeout(() => {
                    quietPrintRef.value?.print2(param);
                  }, i * 100);
                  i++;
                }
              })
            } else {
              proxy.$alert('查无报告模板', '提示');
            }
          })
          .catch((err: any) => {
            proxy.$alert('查询报告模板失败' + err, '提示');
            //VxeMessage('操作失败,请联系管理员', VxeNotifyType.error);
          });
      }

    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}


/**静默打印执行打印 */
function printAction(mainInfo: undefined) {
  proxy.$http
    .post('/api/lab/lab-rptmain/bacGenerateReport', { mainInfoId: form.id, IsFinalRpt: false, rptGroup: form.rptGroup, sampleNo: form.sampleNo, sampleda: form.sampleda + ' 00:00:00' })
    .then((res: any) => {
      let rptNames = [];
      let arr: { ReportName: any; ReportParameters: { Name: string; Value: any }[]; PdfPrinterSetting: { PdfPrinterCopies: number } }[] | null = [];
      res.data.forEach((e: { reportId: any; id: any }) => {
        arr.push({ ReportName: e.reportId, ReportParameters: [{ Name: 'Id', Value: e.id }], PdfPrinterSetting: { PdfPrinterCopies: 1 } });
        rptNames.push(e.reportId);
      });
      printParamsObj.value = arr;

      try {
        /* 记录过程记录 */
        const a = localStorage.getItem('userInfo');
        const b = JSON.parse(a);
        const strainNameStr = `打印报告`;
        const processLogData = {
          strainId: null,
          strainNo: null,
          strainName: strainNameStr,
          maininfoId: form.id,
          wkFlwId: null,
          wkFlwNodeId: null,
          rptGroup: form.rptGroup,
          sampleda: formatDateTime(form.sampleda, 'yyyy-MM-dd 00:00:00'),
          sampleNo: form.sampleNo,
          testFlowNo: curreFlowNode.value.testFlowNo,
          testNodeNo: curreFlowNode.value.nodeNo,
          content: `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】打印报告:${rptNames.filter(Boolean).join(',')}`,
          operatorDoctor: IsEmpty(b.username) ? '' : b.username
        };
        saveProcessLogs(processLogData);
      } catch (error) { }
    })
    .catch((err: any) => {
      VxeMessage('打印失败', VxeNotifyType.error);
    });
}
/**刷新当前选中 */
$this['refreshCurrentRow'] = () => {
  testListRef.value?.refreshMainInfoListM2({ isSelCurRow: false, isRefreshRptResult: true, mainInfoId: currentMainInfo.id });
};
/**预览报告 */
$this['previewRpt'] = () => {
  isPreviewRpt.value = false;
  reportList.length = 0;
  if (IsEmpty(form)) {
    VxeMessage('预览失败', VxeNotifyType.error);
  }
  proxy.$http
    .post('/api/lab/lab-rptmain/bacGenerateReport', { mainInfoId: form.id, IsFinalRpt: false, rptGroup: form.rptGroup, sampleNo: form.sampleNo, sampleda: form.sampleda + ' 00:00:00' })
    .then((res: any) => {
      Object.assign(reportList, res.data);
      isPreviewRpt.value = true;
    })
    .catch((err: any) => {
      VxeMessage('预览失败', VxeNotifyType.error);
    });
};
/**预览初级报告 */
$this['previewFirstRpt'] = (param: any) => {
  isPreviewRpt.value = false;
  reportList.length = 0;
  if (IsEmpty(form)) {
    VxeMessage('预览失败', VxeNotifyType.error);
  }
  proxy.$http
    .post('/api/lab/lab-rptmain/bacGenerateFirstReport', { mainInfoId: form.id, IsFinalRpt: false, rptGroup: form.rptGroup, sampleNo: form.sampleNo, sampleda: form.sampleda + ' 00:00:00', testFlowNo: param.testFlowNo, testNodeNo: param.testNodeNo, culMediumNos: param.culMediumNos })
    .then((res: any) => {
      if (res && res.status.code === 1 && res.data.length > 0 && !IsEmpty(res.data[0].id)) {
        Object.assign(reportList, res.data);
        isPreviewRpt.value = true;
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('预览失败', VxeNotifyType.error);
    });
};
/**预览二级报告 */
$this['previewSecondRpt'] = (param: any) => {
  isPreviewRpt.value = false;
  reportList.length = 0;
  if (IsEmpty(form)) {
    VxeMessage('预览失败', VxeNotifyType.error);
  }
  //增加菌株匹配选择，若菌株号存在，则匹配
  proxy.$http
    .post('/api/lab/lab-rptmain/bacGenerateSecondReport', { mainInfoId: form.id, IsFinalRpt: false, rptGroup: form.rptGroup, sampleNo: form.sampleNo, sampleda: form.sampleda + ' 00:00:00', testFlowNo: param.testFlowNo, testNodeNo: param.testNodeNo, strainNo: param.strainNo })
    .then((res: any) => {
      Object.assign(reportList, res.data);
      isPreviewRpt.value = true;
    })
    .catch((err: any) => {
      VxeMessage('预览失败', VxeNotifyType.error);
    });
};
/**打印初级报告 */
$this['printFirstRpt'] = (param: any) => {
  if (IsEmpty(form)) {
    VxeMessage('请选择一条检验记录', VxeNotifyType.error);
  }
  proxy.$http
    .post('/api/lab/lab-rptmain/bacGenerateFirstReport', { mainInfoId: form.id, IsFinalRpt: false, rptGroup: form.rptGroup, sampleNo: form.sampleNo, sampleda: form.sampleda + ' 00:00:00', testFlowNo: param.testFlowNo, testNodeNo: param.testNodeNo, culMediumNos: param.culMediumNos })
    .then((res: any) => {
      if (res && res.status.code === 1 && res.data.length > 0 && !IsEmpty(res.data[0].id)) {
        let arr: any[] = [];
        let rptNames = [];
        res.data.forEach((e: { reportId: any; id: any }) => {
          arr.push({ ReportName: e.reportId, ReportParameters: [{ Name: 'Id', Value: e.id }], PdfPrinterSetting: { PdfPrinterCopies: 1 } });
          rptNames.push(e.reportId);
        });
        printParamsObj.value = arr;
        try {
          /* 记录过程记录 */
          const a = localStorage.getItem('userInfo');
          const b = JSON.parse(a);
          const strainNameStr = `打印初级报告`;
          const processLogData = {
            strainId: null,
            strainNo: null,
            strainName: strainNameStr,
            maininfoId: form.id,
            wkFlwId: null,
            wkFlwNodeId: null,
            rptGroup: form.rptGroup,
            sampleda: formatDateTime(form.sampleda, 'yyyy-MM-dd 00:00:00'),
            sampleNo: form.sampleNo,
            testFlowNo: param.testFlowNo,
            testNodeNo: 'YQPY',
            content: `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】打印初级报告:${rptNames.filter(Boolean).join(',')}`,
            operatorDoctor: IsEmpty(b.username) ? '' : b.username
          };
          saveProcessLogs(processLogData);
        } catch (error) { }
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('预览失败', VxeNotifyType.error);
    });
};
/**打印二级报告 */
$this['printSecondRpt'] = (param: any) => {
  if (IsEmpty(form)) {
    VxeMessage('请选择一条检验记录', VxeNotifyType.error);
  }
  proxy.$http
    .post('/api/lab/lab-rptmain/bacGenerateSecondReport', { mainInfoId: form.id, IsFinalRpt: false, rptGroup: form.rptGroup, sampleNo: form.sampleNo, sampleda: form.sampleda + ' 00:00:00', testFlowNo: param.testFlowNo, testNodeNo: param.testNodeNo })
    .then((res: any) => {
      if (res && res.status.code === 1 && res.data.length > 0 && !IsEmpty(res.data[0].id)) {
        let arr: any[] = [];
        let rptNames = [];
        res.data.forEach((e: { reportId: any; id: any }) => {
          arr.push({ ReportName: e.reportId, ReportParameters: [{ Name: 'Id', Value: e.id }], PdfPrinterSetting: { PdfPrinterCopies: 1 } });
          rptNames.push(e.reportId);
        });
        printParamsObj.value = arr;

        try {
          /* 记录过程记录 */
          const a = localStorage.getItem('userInfo');
          const b = JSON.parse(a);
          const strainNameStr = `打印二级报告`;
          const processLogData = {
            strainId: null,
            strainNo: null,
            strainName: strainNameStr,
            maininfoId: form.id,
            wkFlwId: null,
            wkFlwNodeId: null,
            rptGroup: form.rptGroup,
            sampleda: formatDateTime(form.sampleda, 'yyyy-MM-dd 00:00:00'),
            sampleNo: form.sampleNo,
            testFlowNo: param.testFlowNo,
            testNodeNo: param.testNodeNo,
            content: `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】打印二级报告:${rptNames.filter(Boolean).join(',')}`,
            operatorDoctor: IsEmpty(b.username) ? '' : b.username
          };
          saveProcessLogs(processLogData);
        } catch (error) { }
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage('预览失败', VxeNotifyType.error);
    });
};
/**打印报告 */
$this['previewPrint'] = async () => {
  /**先把打印前的自动审核标记置为fasle */
  chkBeforePrint.value = false;
  alarmReportBeforeChk.value = false;
  /** 打印前必须审核*/
  const a = getOptionValueByCodeRptGroupOption('dyqbxsh');
  const row = testListRef.value?.getCurrentRecordRow();
  if ((a === '1' || a === 1) && row.isChk < 2) {
    /**打印前自动审核系统选项 */
    const b = getOptionValueByCodeRptGroupOption('dyqzdsh');

    /**【情况一】 打印时不自动审核且改行未审核，提示先审核数据*/
    if (row.isChk < 2 && b !== '1' && b !== 1) {
      VxeMessage('请先审核数据', VxeNotifyType.warning);
      return;
    }

    /** 审核完自动打印*/
    const c = getOptionValueByCodeRptGroupOption('shhzddy');
    /**【情况二】未审核，打印时自动审核,审核后自动打印 */
    if (row.isChk < 2 && (b === '1' || b === 1) /*打印时，未审核，自动审核*/ && (c === '1' || c === 1) /*审核后，自动打印*/) {
      /**先走审核逻辑,不用再走打印 */
      //1、验证审核时 是否弹出危急值上报界面
      //审核时是否弹出危急值上报界面
      const aalarm = getOptionValueByCodeGlobalOption('shstcwjzsbjm'); /**审核时是否弹出危急值界面 shstcwjzsbjm*/

      if (aalarm === '1' || aalarm === 1) {
        if (testListRef.value) {
          const rowMI = testListRef.value?.getCurrentRecordRow();
          if (rowMI && !IsEmpty(rowMI.id) && !IsEmpty(rowMI.isAlarm) && (rowMI.isAlarm === '1' || rowMI.isAlarm === 1)) {
            //是否还有未处理的危急值
            const criNotreat = await isNotreatAlarmReport(rowMI.id);
            if (criticalReportRef.value && criNotreat) {
              alarmReportBeforeChk.value = true;
              chkBeforePrint.value = true;
              criticalReportRef.value?.criticaReportData(rowMI);
              return;
            }
          }
        }
      }

      //2、缓存中，检验医师、审核医师没有过期 则使用缓存中的数据
      if (storeObj.chkDoctorObj && !IsEmpty(storeObj.chkDoctorObj.code)) {
        const curDateTime = new Date().valueOf();
        if (Number(curDateTime) > Number(storeObj.chkDoctorObj.expressin)) {
          if (ChkAuthCompRef.value) {
            ChkAuthCompRef.value?.initPage(true, '审核');
          }
          chkBeforePrint.value = true;
          return;
        }
      } else {
        if (ChkAuthCompRef.value) {
          ChkAuthCompRef.value?.initPage(true, '审核');
        }
        chkBeforePrint.value = true;
        return;
      }

      let resData = { edtType: 1, codeRange: '', action: '2' };
      if (testListRef.value) {
        testListRef.value?.refreshMainInfoListM3(resData);
      }

      /**再判断是否跳转选中下一个标本 */
      /**判断审核后是否自动跳转下一个标本 【shtgzdxybb】*/
      const d = getOptionValueByCodeRptGroupOption('shtgzdxybb');
      /**审核后自动跳转下一个标本，则跳转下一个标本不再执行 */
      if (d === '1' || d === 1) {
        return;
      }

      /**审核后【不】自动跳转下一个标本，则继续执行打印后跳转下一个标本 */
      const e = getOptionValueByCodeRptGroupOption('dyhzdxybb');
      if (e === '1' && e === 1) {
        //跳转下一个标本
        selectNextMainInfoRo();
        return;
      }
    }

    /**【情况三】未审核，打印时自动审核,审核后【不】自动打印 */
    if (row.isChk < 2 && (b === '1' || b === 1) /*打印时，未审核，自动审核*/ && c !== '1' && c !== 1 /*审核后，【不】自动打印*/) {
      /**先走审核逻辑 */
      //1、验证审核时 是否弹出危急值上报界面
      //审核时是否弹出危急值上报界面
      const aalarm = getOptionValueByCodeGlobalOption('shstcwjzsbjm'); /**审核时是否弹出危急值界面 shstcwjzsbjm*/

      if (aalarm === '1' || aalarm === 1) {
        if (testListRef.value) {
          const rowMI = testListRef.value?.getCurrentRecordRow();
          if (rowMI && !IsEmpty(rowMI.id) && !IsEmpty(rowMI.isAlarm) && (rowMI.isAlarm === '1' || rowMI.isAlarm === 1)) {
            //是否还有未处理的危急值
            const criNotreat = await isNotreatAlarmReport(rowMI.id);
            if (criticalReportRef.value && criNotreat) {
              alarmReportBeforeChk.value = true;
              chkBeforePrint.value = true;
              criticalReportRef.value?.criticaReportData(rowMI);
              return;
            }
          }
        }
      }

      //2、缓存中，检验医师、审核医师没有过期 则使用缓存中的数据
      if (storeObj.chkDoctorObj && !IsEmpty(storeObj.chkDoctorObj.code)) {
        const curDateTime = new Date().valueOf();
        if (Number(curDateTime) > Number(storeObj.chkDoctorObj.expressin)) {
          if (ChkAuthCompRef.value) {
            ChkAuthCompRef.value?.initPage(true, '审核');
          }
          chkBeforePrint.value = true;
          return;
        }
      } else {
        if (ChkAuthCompRef.value) {
          ChkAuthCompRef.value?.initPage(true, '审核');
        }
        chkBeforePrint.value = true;
        return;
      }

      let resData = { edtType: 1, codeRange: '', action: '2' };
      if (testListRef.value) {
        testListRef.value?.refreshMainInfoListM3(resData);
      }
      /**再走打印处理 */
      printAction();

      /**最后判断是否跳转选中下一个标本 */
      /**判断审核后是否自动跳转下一个标本 【shtgzdxybb】*/
      const d = getOptionValueByCodeRptGroupOption('shtgzdxybb');
      /**审核后自动跳转下一个标本，则跳转下一个标本不再执行 */
      if (d === '1' || d === 1) {
        return;
      }

      /**审核后【不】自动跳转下一个标本，则继续执行打印后跳转下一个标本 */
      const e = getOptionValueByCodeRptGroupOption('dyhzdxybb');
      if (e === '1' && e === 1) {
        //跳转下一个标本
        selectNextMainInfoRo();
        return;
      }
    }
    return;
  }
  /**打印前不必审核 */
  printAction();

  /**打印后跳转下一个标本 */
  const e = getOptionValueByCodeRptGroupOption('dyhzdxybb');
  if (e === '1' || e === 1) {
    //跳转下一个标本
    selectNextMainInfoRo();
    return;
  }
};
/**上一个 */
$this['prevCode'] = (isCallMainInfo = true) => {
  const a = autoIncrementNumber(form.sampleNo, '-');
  form.sampleNo = a;
  form.reqNo = '';
  if (isCallMainInfo) {
    testListRef.value?.baseInfoChange(3, a, form, async () => {
      //#region  Name
      if (true) {
        /**没有选中，查询数据库，是否是否有该条记录 */
        const res = await testListRef.value?.findLabMainInfoByPrimaryData(form.rptGroup, form.sampleda, form.sampleNo);
        if (res && res.length > 0) {
          Object.assign(form, res[0]);
          Object.assign(currentMainInfo, res[0]);
          bacMainInfoEditPanelRef.value?.currentMainInfoChange(res[0]);
          if (RptResultBacRef.value) {
            RptResultBacRef.value?.initTestList(form, false); //传递给右侧基本信息表单
          }
        }
        if (!res) {
          /**如果下一个标本，则清空中间结果 */
          clearPatResultInfos();
        }
      }
      //#endregion
    });
  }
};
/**下一个 */
$this['nextCode'] = (isCallMainInfo = true) => {
  const a = autoIncrementNumber(form.sampleNo, '+');
  //const a = getBacSampleNo();
  form.sampleNo = a;
  form.reqNo = '';
  if (isCallMainInfo) {
    testListRef.value?.baseInfoChange(3, a, form, async () => {
      //#region  Name
      if (true) {
        /**没有选中，查询数据库，是否是否有该条记录 */
        const res = await testListRef.value?.findLabMainInfoByPrimaryData(form.rptGroup, form.sampleda, form.sampleNo);
        if (res && res.length > 0) {
          Object.assign(form, res[0]);
          Object.assign(currentMainInfo, res[0]);
          bacMainInfoEditPanelRef.value?.currentMainInfoChange(res[0]);
          if (RptResultBacRef.value) {
            RptResultBacRef.value?.initTestList(form, false); //传递给右侧基本信息表单
          }
        } else {
          reqNoInput.value?.focus();
        }
        if (!res) {
          /**如果下一个标本，则清空中间结果 */
          clearPatResultInfos();
        }
      }
      //#endregion
    });
  }
};
/**当检验记录为空时 清空左侧人员信息，中间结果列表数据 */
function clearPatResultInfos() {
  form.id = null;
  Object.keys(form).forEach((k) => {
    if (k === 'rptGroup' || k === 'sampleda' || k === 'sampleNo') {
      //ToDo
    } else {
      form[k] = null;
      if (currentMainInfo && currentMainInfo[k]) {
        currentMainInfo[k] = null;
      }
    }
  });
  bacMainInfoEditPanelRef.value?.currentMainInfoChange(form);
  if (RptResultBacRef.value) {
    RptResultBacRef.value?.initTestList(form); //传递给右侧基本信息表单
  }
  imageRef.value.getImageData(form);
  costRef.value.getreqDetail(form);
  LabMainInfoLogRef.value.initForm(form);
}

const scanCodeForm = reactive({
  id: '',
  sampleNo: '1',
  visible: false,
  rptGroup: '',
  sampleda: '',
  dataType: '2' /**业务类型，普通检验 */,
  wl: []
});


//批量扫码
$this['scanCodeBulk'] = () => {
  form['dataType'] = '2';
  scanCodeForm.id = form.id;
  scanCodeForm.rptGroup = form.rptGroup;
  scanCodeForm.sampleNo = form.sampleNo;
  scanCodeForm.sampleda = form.sampleda;
  scanCodeForm.visible = true;
  bacScanCodeDlgRef.value?.wkltData(scanCodeForm);
};
/**初级报告 */
$this['prelReport'] = () => {
  //todo
};
/**审核 */
$this['chkMainInfo'] = () => {
  if (storeObj.chkDoctorObj) {
    const curDateTime = new Date().valueOf();
    if (Number(curDateTime) > Number(storeObj.chkDoctorObj.expressin)) {
      if (ChkAuthCompRef.value) {
        ChkAuthCompRef.value?.initPage(true, '审核');
      }
      storeObj.clearChkDoctorObj();
      return;
    }
    let resData = { edtType: 1, codeRange: '', action: '2' };
    if (testListRef.value) {
      testListRef.value?.refreshMainInfoListM3(resData);
    }
    return;
  }
  if (ChkAuthCompRef.value) {
    ChkAuthCompRef.value?.initPage(true, '审核');
  }
};
/**取消审核 */
$this['unChkMainInfo'] = () => {
  /**消审操作人需再登录 xsczrxyzdl */
  const a = getOptionValueByCodeGlobalOption('shstcwjzsbjm'); /**消审操作人需再登录 xsczrxyzdl*/
  if (a && (a === '1' || a === 1)) {
    if (AuthValidateCompRef.value) {
      AuthValidateCompRef.value?.initPage(true, '取消审核验证');
      return;
    }
  }
  if (testListRef.value) {
    testListRef.value?.unChkMainInfo(currentMainInfo);
  }
};

function currentRow(row) {
  testListRef.value?.refreshMainInfoListM4(row.id);
}

/**360患者视图 */
$this['getWlEhrName'] = () => {
  const url = '/api/sys/hisEmployee/getInterfaceData';
  const params = {
    url: '/EHR/getEHRByIdNo',
    code: 'GET_EHR',
    idNo: form.idNo,
    patNo: form.patNo,
    reqNo: form.reqNo
  };
  proxy.$http
    .get(url, { params: params })
    .then((res: any) => {
      if (!IsEmpty(JSON.parse(res.data).data)) {
        window.open(JSON.parse(res.data).data);
      }
    })
    .catch((err: any) => {
      VxeMessage('同步失败', VxeNotifyType.error);
    });
};

/**取消审核验证成功返回 */
function unChkConfirm(e: any) {
  if (testListRef.value) {
    testListRef.value?.unChkMainInfo(currentMainInfo, e);
  }
}
/**审核确认 */
function chkConfirm(e: any) {
  /**只修改当前标本 e.edtType===1*/
  /**修改所有未审核标本 e.edtType===2*/
  /**修改指定标本号范围 e.edtType===3*/
  testListRef.value?.refreshMainInfoListM3(e);

  /** 如果是打印前自动审核，审核后，需要判断下是否跳转下一个标本*/
  // if (chkBeforePrint.value) {
  //   isNextMainInfoSelection();
  // }
}
/**插入流程方案 */
function insertWkflw() {
  WkflwSelectionRef.value?.showModal(currentMainInfo);
}
/**批量扫码执行成功更新检验主记录 */
function refreshLabMinInfo(e: any) {
  //todo
}
/**危急值处理完成 */
function alarmTreatFinish() {
  if (alarmReportBeforeChk.value && !chkBeforePrint.value) {
    $this['chkMainInfo']();
  }
  if (alarmReportBeforeChk.value && chkBeforePrint.value) {
    $this['previewPrint']();
  }
}
/**下一个标本，有中间动作(例如：审核、上报危急值等等)中间处理完成后,跳转下一个 */
function selectNextMainInfoRo() {
  if (testListRef.value) {
    const row = testListRef.value?.getCurrentRecordRow();
    testListRef.value?.nextRowSelected(row);
  }
}
/**选择药敏模板 */
function selectBacDrugResultTemplate() {
  BacDrugResultTempModalRef.value?.showModal();
}

/**转种 */
function subcultivation(row) {
  //调用RptCultiObserResultRef组件方法
  RptCultiObserResultRef.value?.cultureSubcultivation(row);
}

/**镜检结果录入 */
function insertCultiResult() {
  RptCultiObserResultRef.value?.showModal();
}

/**镜检结果录入 */
function insertCultiResult2() {
  RptCultiObserResultRef.value?.showModal2();
}

/**镜检结果录入 */
function insertCultiResult3() {
  RptCultiObserResultRef.value?.showModal3();
}

/**镜检结果录入 */
function insertCultiResult4() { }

/**药敏模板确认选中 */
function drugTemplateConfirm(rows: any) {
  if (RptResultBacRef.value) {
    RptResultBacRef.value?.drugResultTempLdateQuickInsert(rows);
  }
}
/**镜检截图选中回调 */
function imgSelectedCallback() {
  RptCultiObserResultRef.value?.imgSelectedCallback();
}
/**切换方案成功 */
function changeSuccess() {
  $this['refreshCurrentRow']();
}
/**判断是否审核，若审核范围ture */
function resultIsDisabled() {
  if (!IsEmpty(currentMainInfo) && currentMainInfo.isChk == '2') {
    return true;
  } else {
    return false;
  }
}
/* 报告汇总打印报告 */
function rptOverviewPrintReport(arr: any[]) {
  printParamsObj.value = arr;
}

function getAddFeeCnt(data) {
  testListRef.value?.getAddFeeCnt(data);
  flowStepCompRef.value?.getAddFeeCnt(data);
}
//传值到Template.vue界面
function templateClick(e) {
  if (LabMainInfoLogRef.value && !IsEmpty(e.index) && `${e.index}` === '4') {
    LabMainInfoLogRef.value.initForm(form);
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/el-tabs.scss';

.cursor {
  cursor: pointer;
}

.rpt-group-setting:hover {
  color: blue;
}

#labmaininfobac {
  height: 100%;

  .bodyContent {
    height: calc(100% - 20px);

    .area {
      background-color: $base-white;

      .Splitpanes-Panel {
        height: calc(100vh - 75px);
      }

      .lab-maininfo-right-tab {
        height: 100%;

        :deep(.el-tabs__nav-prev) {
          line-height: 28px !important;
        }

        :deep(.el-tabs__nav-next) {
          line-height: 28px !important;
        }

        :deep(.el-tabs__content) {
          height: calc(100% - 30px);
          padding: 2px;
        }

        :deep(.el-tab-pane) {
          height: 100%;
        }
      }
    }
  }
}

:deep(.el-tabs__new-tab) {
  margin: unset;
  width: unset;
  border: unset;
  margin-top: 3px;
}

:deep(.el-tabs--card > .el-tabs__header) {
  height: unset;
}

:deep(.el-tabs__header) {
  margin: unset;
}
</style>
